<template>
  <a-modal v-model="equipmentPop" width="50%" title="修改设备绑定" centered @cancel="closeFn" @ok="SubmitFn" :maskClosable="false" destroyOnClose>
    <div class="equipmentClass">
      <a-input-search style="margin-bottom: 8px;width:50%;" placeholder="请输入要查找的企业名称" @change="onChange"/>
      <a-tree
          v-model="equipmentArr"
          v-if="dataLoading"
          checkable
          :auto-expand-parent="autoExpandParent"
          :expanded-keys="expandedKeys"
          :tree-data="equipmentTreeData"
          :replaceFields="{children:'equipmentInfos',title:'name',key:'id'}"
          @check="onSelect"
          @expand="onExpand"
      >
        <template slot="name" slot-scope="{name,id}">
        <span v-if="name.indexOf(searchValue) > -1">
          {{ name.substr(0, name.indexOf(searchValue))}}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ name.substr(name.indexOf(searchValue) + searchValue.length)}}
        </span>
          <span v-else>{{ name }}</span>
        </template>

      </a-tree>
    </div>
<!--    <template slot="footer">-->
<!--      <a-button type="primary" @click="SubmitFn">确定</a-button>-->
<!--    </template>-->
  </a-modal>
</template>

<script>
const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.equipmentInfos) {
      if (node.equipmentInfos.some(item => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.equipmentInfos)) {
        parentKey = getParentKey(key, node.equipmentInfos);
      }
    }
  }
  return parentKey;
};
export default {
  name: "EquipmentPop.vue",
  props:{
    equipmentPopData:{type:Object,required:true}
  },
  data() {
    return {
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataList:[],
      // 测试
      // userId: "",
      dataLoading:false,
      equipmentPop: false,
      equipmentTreeData: [],  // 树形架构数据
      equipmentArr: [],   //  用户选取的树形
      equipmentTreeDatas:[],
      cloneTreeData:[],  // 克隆树形数据
      cloneequipmentArr:[]  // 克隆用户已勾选数据
    }
  },
  methods: {
    generateList(data){
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.id;
        this.dataList.push({ key, title: node.name });
        if (node.equipmentInfos&&node.equipmentInfos != []) {
          this.generateList(node.equipmentInfos);
        }
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      const value = e.target.value;
      this.equipmentArr = JSON.parse(JSON.stringify(this.cloneequipmentArr))
      console.log(value?true:false)
      // const mapData = [];
      let mapData = this.cloneTreeData[0].equipmentInfos.filter(item=>{
        if(item.name.includes(value)){
          return item;
        }
      })

      this.equipmentTreeData[0].equipmentInfos = mapData;
      console.log(this.equipmentArr)
      // const expandedKeys = this.dataList.map(item => {
      //       if (item.title.indexOf(value) > -1) {
      //         console.log(item.key)
      //         return getParentKey(item.key, this.equipmentTreeData);
      //       }
      //       return null;
      //     }).filter((item, i, self) => item && self.indexOf(item) === i);
      // Object.assign(this, {
      //   expandedKeys,
      //   searchValue: value,
      //   autoExpandParent: true,
      // });
    },
    // 测试
    onSelect(selectedKeys, info) {
      console.log(selectedKeys, info,this.equipmentTreeData)
      console.log(info.node.eventKey,info.node.checked,this.cloneequipmentArr)
      this.equipmentTreeData[0].equipmentInfos.forEach(v=>{
        if(!info.node.checked){
          if(info.node.eventKey == 'Selectall'){
            if(!this.cloneequipmentArr.includes(v.id)){
              this.cloneequipmentArr.push(v.id)
            }
            v.equipmentInfos.forEach(item=>{
              if(!this.cloneequipmentArr.includes(item.id)){
                this.cloneequipmentArr.push(item.id)
              }
            })
          }else {
            if(v.id == info.node.eventKey){
              // if(!this.cloneequipmentArr.includes(info.node.eventKey)){
              //   this.cloneequipmentArr.push(info.node.eventKey)
              // }
              v.equipmentInfos.forEach(item=>{
                if(!this.cloneequipmentArr.includes(item.id)){
                  this.cloneequipmentArr.push(item.id)
                }
              })
            }else {
              // info.halfCheckedKeys.forEach(j=>{
              //   if(!this.cloneequipmentArr.includes(j)){
              //     if(j != 'Selectall'){
              //       this.cloneequipmentArr.push(j);
              //     }
              //   }
              // })

              if(!this.cloneequipmentArr.includes(info.node.eventKey)){
                this.cloneequipmentArr.push(info.node.eventKey)
              }
            }
          }
        }else {
          if(info.node.eventKey == 'Selectall'){
            let indexKey = this.cloneequipmentArr.indexOf(v.id);
            if(indexKey != -1){
              this.cloneequipmentArr.splice(indexKey,1)
            }
            v.equipmentInfos.forEach(item=>{
              if(this.cloneequipmentArr.indexOf(item.id) != -1){
                this.cloneequipmentArr.splice(this.cloneequipmentArr.indexOf(item.id),1)
              }
            })
          }else {
            if(v.id == info.node.eventKey){
              let indexKey = this.cloneequipmentArr.indexOf(info.node.eventKey);
              if(indexKey != -1){
                this.cloneequipmentArr.splice(indexKey,1)
              }
              v.equipmentInfos.forEach(item=>{
                if(this.cloneequipmentArr.indexOf(item.id) != -1){
                  this.cloneequipmentArr.splice(this.cloneequipmentArr.indexOf(item.id),1)
                }
              })
            }else {
              // v.equipmentInfos.forEach(j=>{
              //   if(j.id == info.node.eventKey){
              //     if(!info.halfCheckedKeys.includes(v.id)){
              //       this.cloneequipmentArr.splice(this.cloneequipmentArr.indexOf(v.id),1)
              //     }
              //   }
              // })
              // info.halfCheckedKeys.forEach(j=>{})

              let indexKey = this.cloneequipmentArr.indexOf(info.node.eventKey);
              if(indexKey != -1){
                this.cloneequipmentArr.splice(indexKey,1)
              }
            }
          }
        }
      })
      console.log(this.cloneequipmentArr)
      // console.log(...arguments,this.equipmentArr);
    },
    // 提交表单
    SubmitFn() {
      this.equipmentArr == this.cloneequipmentArr;
      let arr = {
        userId: this.equipmentPopData.userId,
        monitorIds: []
      }
      this.cloneTreeData[0].equipmentInfos.forEach(item=>{
        item.equipmentInfos.forEach(v=>{
          this.cloneequipmentArr.forEach(j=>{
            if(j == v.id){
              let obj = {
                companyId: item.id,
                monitorId: j
              }
              arr.monitorIds.push(obj)
            }
          })
        })
      })
      console.log(arr)
      // return
      this.$api.monitorUserBindMonitor(arr).then(res => {
        if (res.data.code == 0) {
          this.equipmentPop = false;
          this.equipmentArr = [];
          this.equipmentTreeDatas = [];
          this.expandedKeys = [];
          this.searchValue = '';
          this.autoExpandParent = true;
          this.dataList = [];
          this.$message.info(res.data.errorMessage);

        }
      })
    },
    // 弹窗关闭
    closeFn() {
      this.equipmentArr = [];
      this.equipmentTreeDatas = [];
      this.expandedKeys = [];
      this.searchValue = '';
      this.autoExpandParent = true;
      this.dataList = [];
      this.equipmentPop = false;
    },
    // 树形初始化数据
    // 添加slot
    addslot(data){
      data.forEach(v=>{
        v.scopedSlots={ title: 'name' };
        if(v.equipmentInfos){
          this.addslot(v.equipmentInfos)
        }
      })
      return data
    },
    init() {
      this.$api.equipmentGetEquipmentIdByUserId(this.equipmentPopData).then((res) => {
        if (res.data.code == 0) {
          const selectData = []
          this.equipmentTreeDatas = this.addslot(res.data.data)
          this.generateList(res.data.data)
          res.data.data.forEach(v => {
            v.equipmentInfos.forEach(item => {
              if (item.isChecked) {
                selectData.push(item.id);
              }
            })
          })
          if(res.data.data.length>0){
            this.equipmentTreeData = [{
              id: "Selectall",
              name: "全选",
              equipmentInfos: res.data.data
            }]
            this.equipmentArr = JSON.parse(JSON.stringify(selectData))
            this.cloneequipmentArr = JSON.parse(JSON.stringify(selectData))
            this.cloneTreeData = JSON.parse(JSON.stringify(this.equipmentTreeData));
          }else {
            this.equipmentTreeData = res.data.data;
            this.$message.info("暂无可绑定的排口")
          }

          this.dataLoading = true;
        } else {
          this.$message.info(res.data.errorMessage);
        }
      });
    }
  },
  mounted() {
  }
}
</script>

<style scoped lang="scss">
.equipmentClass {
  height: 500px;
  overflow-y: auto;

}
</style>